package lotus.blog.lotusblog.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import lotus.blog.lotusblog.mapper.ArticleMapper;
import lotus.blog.lotusblog.mapper.CommentMapper;
import lotus.blog.lotusblog.mapper.UserMapper;
import lotus.blog.lotusblog.pojo.Article;
import lotus.blog.lotusblog.pojo.Comment;
import lotus.blog.lotusblog.pojo.User;
import lotus.blog.lotusblog.utils.JwtUtil;
import lotus.blog.lotusblog.utils.ResultTemplate;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("comment")
public class CommentController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    JwtUtil jwtUtil;
    @PostMapping("/add")
    public ResultTemplate add(@RequestBody Comment comment, HttpServletRequest request){
        if (jwtUtil.getUserBytoken(request).getId() != comment.getUserId() || (comment.getRepliedId() != 0 && commentMapper.selectById(comment.getRepliedId()).getArticleId()!=comment.getArticleId())){
            return ResultTemplate.authFail("非法信息传递");
        }
        comment.setReleaseTime(String.valueOf(System.currentTimeMillis()));
        try {
            commentMapper.insert(comment);
        }catch (Exception e){
            e.printStackTrace();
            return ResultTemplate.fail("添加失败");
        }
        return  ResultTemplate.succ("添加成功");
    }
    @GetMapping("/getList")
    public ResultTemplate getList(@RequestParam("article_id")int articleId){
        List<Map<String,Object>> list = commentMapper.getCommentList(articleId);
        return ResultTemplate.succ("获取成功",list);
    }
    @PostMapping("delete")
    public ResultTemplate delete(@RequestBody Comment comment,HttpServletRequest request){
        User user = jwtUtil.getUserBytoken(request);
        if(articleMapper.selectById(comment.getArticleId()).getUserId() != user.getId()&&user.getId()!=comment.getUserId()){
            return ResultTemplate.authFail("非法信息");
        }
        try{
            commentMapper.deleteById(comment);
        }catch (Exception e){
            return ResultTemplate.authFail("删除失败");
        }
        return ResultTemplate.succ("删除成功");


    }
}
